@tool
class_name Unit
extends Area2D

# ===============================================

signal quick_sell_pressed()

# ===============================================

@export var stats: UnitStats :
	set(value):
		stats = value
		if value == null or not is_instance_valid(tier_icon):
			return
		if not Engine.is_editor_hint():
			stats = value.duplicate()
		skin.coordinates = stats.skin_coordinates
		tier_icon.stats = stats

# ===============================================

@onready var skin: PackedSprite2D = $Visuals/Skin
@onready var health_bar: ProgressBar = $HealthBar
@onready var mana_bar: ProgressBar = $ManaBar
@onready var tier_icon: TierIcon = $TierIcon
@onready var drag_and_drop: DragAndDrop = $DragAndDrop
@onready var velocity_based_rotation: VelocityBasedRotation = $VelocityBasedRotation
@onready var outline_highlighter: OutlineHighlighter = $OutlineHighlighter
@onready var animation: UnitAnimation = $UnitAnimation

# ===============================================

var is_hovered: bool = false

# ===============================================

func reset_after_dragging(starting_position: Vector2) -> void:
	velocity_based_rotation.enabled = false
	global_position = starting_position

# ===============================================

func _ready() -> void:
	# 在编辑器不执行
	if not Engine.is_editor_hint():
		drag_and_drop.drag_started.connect(func(): velocity_based_rotation.enabled = true)
		drag_and_drop.drag_canceled.connect(reset_after_dragging)


func _on_mouse_entered() -> void:
	if drag_and_drop.dragging:
		return
	outline_highlighter.highlight()
	z_index = 1
	is_hovered = true


func _on_mouse_exited() -> void:
	if drag_and_drop.dragging:
		return
	outline_highlighter.clear_highlight()
	z_index = 0
	is_hovered = false


func _input(event: InputEvent) -> void:
	if is_hovered and event.is_action_pressed("quick_sell"):
		quick_sell_pressed.emit()
